package com.jas.logic;

import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParameterTokenizer {

	private ArrayList<String> listOfTokens;
	private int nextTokenIndex;
	
	//@author a0118677r
	public ParameterTokenizer(String stringToTokenize, String delimiterRegex){
		listOfTokens = tokenizeString(stringToTokenize, delimiterRegex);
		nextTokenIndex = 0;
	}
	
	//@author a0118677r
	private ArrayList<String> tokenizeString(String stringToTokenize, String delimiterRegex){
		ArrayList<String> resultingListOfTokens = new ArrayList<String>();
		if(stringToTokenize == ""){
			return resultingListOfTokens;
		}
		
		Pattern patternToMatch = Pattern.compile(delimiterRegex);
		String[] parameters = patternToMatch.split(stringToTokenize);
		Matcher matcher = patternToMatch.matcher(stringToTokenize);
		
		int counter = 0;
		if(parameters.length > 0 && parameters[counter].equals("")){
			counter++;
		}
		if(parameters.length > counter && stringToTokenize.startsWith(parameters[counter])){
			resultingListOfTokens.add(parameters[counter]);
			counter++;
		}
		while(matcher.find()){
			resultingListOfTokens.add(matcher.group());
			if(counter < parameters.length && !parameters[counter].matches("\\s+")){
				resultingListOfTokens.add(parameters[counter]);
			}
			counter++;
		}
		
		return resultingListOfTokens;
	}
	
	//@author a0118677r
	public boolean hasMoreTokens(){
		if(nextTokenIndex >= listOfTokens.size()){
			return false;
		}else{
			return true;
		}
	}
	
	//@author a0118677r
	public String nextToken(){
		if(nextTokenIndex < listOfTokens.size()){
			String nextToken = listOfTokens.get(nextTokenIndex);
			nextTokenIndex++;
			return nextToken;
		}else{
			throw new NoSuchElementException();
		}
	}
}
